import React, {useCallback, useEffect, useState} from "react"
import styles from "./DirectSaleOrderPage.module.sass"
import {Button, Form, Select, Table} from "antd";
import {PlusOutlined} from "@ant-design/icons";
import FormDrawer from "../../components/FormDrawer";
import DataPageLayout from "../../components/DataPageLayout";
import AuthorizationResource from "../../components/AuthorizationResource";
import {NumberIdAndName} from "../../types/BasicModels";
import {
    createDirectSaleOrder,
    getAllDirectSaleOrderCreatedEmployees,
    QueryDirectSaleOrderResponse,
    queryDirectSaleOrders
} from "../../apis/DirectSaleOrderApi";
import {Pageable} from "../../utils/Page";
import {mergePaginationAndPageable, useTableFilterDateRangeColumnProps} from "../../utils/AntdTableUtils";
import {LocalDate} from "@js-joda/core";
import {observerDashboardPageWrapper} from "../../components/dashboardPages/ObserverDashboardPageWrapper";
import {createDirectSaleClient, getAllDirectSaleClient} from "../../apis/DirectSaleClientApi";
import {useNavigate} from "react-router-dom";
import {useSearchParams} from "react-router-dom";
import {YEAR_MONTH_DAY_FORMATER} from "../../utils/Date";
import QuickCreatableSelectFormItem from "../QuickCreatableSelectFormItem";
import {FormInstance} from "antd/es/form/hooks/useForm";

export interface pageProps {

}

export interface DirectSaleOrderFormData {
    clientId: number
}


const DirectSaleOrderPage: React.FC<pageProps> = (props) => {

    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryDirectSaleOrderResponse[]>([])
    const [loading, setLoading] = useState(false)
    const [totalElements, setTotalElements] = useState(0)
    let [urlSearchParams] = useSearchParams();
    const [clientIds, setClientIds] = useState<number[]>(urlSearchParams.getAll("clientIds").map(it => parseInt(it)))
    const [employeeIds, setEmployeeIds] = useState<number[]>([])


    const [clients, setClients] = useState<Array<NumberIdAndName>>([])

    function queryAllDirectSaleClient() {
        return getAllDirectSaleClient().then(response => {
            setClients(response.data)
        })
    }

    useEffect(() => {
        queryAllDirectSaleClient();
    }, []);

    const [openAddDrawer, setOpenAddDrawer] = useState(false)

    const [startDate, setStartDate] = useState<string>()
    const [endDate, setEndDate] = useState<string>()
    const query = useCallback(() => {
        setLoading(true)
        queryDirectSaleOrders({
            clientIds,
            employeeIds,
            startDate: startDate ? LocalDate.parse(startDate).toString() : undefined,
            endDate: endDate ? LocalDate.parse(endDate).toString() : undefined,
        }, pageable).then(response => {
            setData(response.data.content)
            setTotalElements(response.data.totalElements)
        }).finally(() => {
            setLoading(false)
        })
    }, [...pageable.toDependencyList(), clientIds, employeeIds, startDate, endDate])
    useEffect(() => {
        query()
    }, [query]);
    const [createdByEmployees, setCreatedByEmployees] = useState<NumberIdAndName[]>([])
    useEffect(() => {
        getAllDirectSaleOrderCreatedEmployees().then(response => response.data).then(setCreatedByEmployees)
    }, []);

    function buildFormItems(formInstance: FormInstance) {
        return <>
            <QuickCreatableSelectFormItem name={"clientId"} label={"客户"}
                                          onRefresh={queryAllDirectSaleClient}
                                          options={clients.map(it => ({label: it.name, value: it.id,}))}
                                          onCreate={async (name) => {
                                              let id = (await createDirectSaleClient({name})).data;
                                              clients.push({id, name})
                                              setClients(Array.from(clients))
                                              formInstance.setFieldValue("clientId", id)
                                          }}/>
        </>
    }

    let navigate = useNavigate();
    let [addForm] = Form.useForm();
    return <>
        <DataPageLayout rightActions={<AuthorizationResource authorities={["经销_开单"]}>
            <Button type={"primary"} onClick={() => {
                setOpenAddDrawer(true)
            }}><PlusOutlined/>下单</Button>
        </AuthorizationResource>}>
            <Table<QueryDirectSaleOrderResponse> className={styles.table} onRow={item => {
                return {
                    onClick: () => {
                        navigate(`/directSales/orders/${item.id}`)
                    }
                }
            }} size={"small"} loading={loading} dataSource={data} rowKey={"id"} pagination={{
                current: pageable.page,
                pageSize: pageable.size,
                total: totalElements,
            }} onChange={(pagination, filters, sorter) => {
                setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
                setClientIds(filters["client.name"] as number[])
                setEmployeeIds(filters["createdBy.name"] as number[])
            }}>
                <Table.Column<QueryDirectSaleOrderResponse> filteredValue={clientIds} dataIndex={["client", "name"]}
                                                            title={"客户"}
                                                            filters={clients.map(client => {
                                                                return {
                                                                    text: client.name,
                                                                    value: client.id,
                                                                }
                                                            })} render={(_, record) => {
                    return record.client.name
                }}/>
                <Table.Column dataIndex={"createdDateTime"} title={"下单时间"}
                              {...useTableFilterDateRangeColumnProps<QueryDirectSaleOrderResponse>("createdDateTime", {
                                  handleSearch: value => {
                                      setStartDate(value ? value[0].format() : undefined)
                                      setEndDate(value ? value[1].format() : undefined)
                                  }
                              })}
                              render={(value) => LocalDate.parse(value).format(YEAR_MONTH_DAY_FORMATER)}/>
                <Table.Column dataIndex={["goodsKindAmount"]} title={"单品数量"}/>
                <Table.Column dataIndex={["shouldPaidPrice"]} title={"应收费用"}/>
                <Table.Column dataIndex={["paidPrice"]} title={"已收费用"}/>
                <Table.Column<QueryDirectSaleOrderResponse> dataIndex={["status"]} title={"状态"}
                                                            render={(_, record) => {
                                                                if (record.submittedDateTime == null) {
                                                                    return "待提交"
                                                                } else if (record.paidPrice < record.shouldPaidPrice) {
                                                                    return "待收款"
                                                                } else {
                                                                    return <>
                                                                        已收款
                                                                        <span></span>
                                                                    </>
                                                                }
                                                            }}/>
                <Table.Column dataIndex={["createdBy", "name"]}
                              title={"下单人员"}
                              filters={createdByEmployees.map(it => ({
                                  text: it.name,
                                  value: it.id
                              }))}/>
            </Table>
        </DataPageLayout>
        <FormDrawer<DirectSaleOrderFormData> form={addForm} onClose={() => setOpenAddDrawer(false)}
                                             title={"下单"}
                                             onConfirm={async (values) => {
                                                 return createDirectSaleOrder(values.clientId).then(response => {
                                                     setOpenAddDrawer(false)
                                                     navigate(`/directSales/orders/${response.data}`)
                                                     // query()
                                                 })
                                             }}
                                             open={openAddDrawer}>
            {buildFormItems(addForm)}
        </FormDrawer>
    </>
}
export default observerDashboardPageWrapper(DirectSaleOrderPage, "directSales/orders", "经销")
